package com.mall.order.services;

import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  cskaoyan
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	StockMapper stockMapper;
	@Autowired
	OrderItemMapper itemMapper;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	@Override
	public int deleteOrder(String id) {
		Order order = new Order();
		order.setOrderId(id);
		int rows = orderMapper.delete(order);
		return rows;
	}

	@Override
	public int cancelOrder(String orderId) {
		int rows = orderMapper.updateOrderStatus(orderId, 7);
		return rows;
	}



	/**
	 *  支付成功时，更新订单状态，更新锁定库存
	 * @param request
	 * @return
	 */
	@Override
	public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {
		PayOrderSuccessResponse payOrderSuccessResponse = new PayOrderSuccessResponse();
		String orderId = request.getOrderId();
		//订单表
		Order order = new Order();
		order.setStatus(1);
		order.setPaymentType(1);
		order.setPaymentTime(new Date());
		Example example = new Example(Order.class);
		example.createCriteria().andEqualTo("orderId", orderId);
		orderMapper.updateByExampleSelective(order,example);
		//根据订单号在item表中查出该订单下所有商品的数量,然后挨个改库存
		Example exampleItem = new Example(OrderItem.class);
		exampleItem.createCriteria().andEqualTo("orderId",orderId);
		List<OrderItem> orderItems = itemMapper.selectByExample(exampleItem);

		for (OrderItem orderItem : orderItems) {
			Integer num = orderItem.getNum();
			Long itemId = orderItem.getItemId();
			//根据itemid减少对应锁定库存,
			Example exampleStock = new Example(Stock.class);
			exampleStock.createCriteria().andEqualTo("itemId",itemId);

			Stock stock = stockMapper.selectByPrimaryKey(itemId);
			int defNum = stock.getLockCount() - num;
			if (defNum<0){
				log.error("订单锁定库存存在问题,导致购买后减少锁定库存数量的时候小于零");
			}
			stock.setLockCount(defNum);
			Example exampleStockDes = new Example(Stock.class);
			exampleStock.createCriteria().andEqualTo("itemId",itemId);
		//更新库存表
			stockMapper.updateByExampleSelective(stock,exampleStockDes);
		}
		payOrderSuccessResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
		payOrderSuccessResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

		return payOrderSuccessResponse;
	}

	@Override
	public List<OrderItemResponse> getAllItem(String orderId) {
		ArrayList<OrderItemResponse> orderItemResponses = new ArrayList<>();
		Example example = new Example(OrderItem.class);
		example.createCriteria().andEqualTo("orderId",orderId);

		List<OrderItem> orderItems = itemMapper.selectByExample(example);
		for (OrderItem orderItem : orderItems) {
		OrderItemResponse orderItemResponse = new OrderItemResponse();
			BeanUtils.copyProperties(orderItem,orderItemResponse);
			orderItemResponse.setPrice(BigDecimal.valueOf(orderItem.getPrice()));
			orderItemResponses.add(orderItemResponse);
		}
		return orderItemResponses;



	}
}
